package com.atguigu.gulimall.member.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author: xuesm
 * @date: 2025/2/23 16:47
 */
@Configuration
public class GuliFeignConfig {

    @Bean("requestInterceptor")
    public RequestInterceptor requestTemplate(){
        return new RequestInterceptor(){
            @Override
            public void apply(RequestTemplate requestTemplate) {
                System.out.println("request interceptor线程..." + Thread.currentThread().getId());
                // RequestContextHolder 拿到刚刚进来的请求
                ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                if (attributes != null){
                    HttpServletRequest request = attributes.getRequest(); // 老请求
                    if (request != null){
                        String cookie = request.getHeader("Cookie");
                        // 给新请求同步老请求的cookie
                        requestTemplate.header("Cookie", cookie);
                    }
                }

            }
        };
    }
}
